package com.fhz.netty.server.websocket.utils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.util.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ChannelSupervise {
    public static final String KEY_USER_ID = "userId";
    public static final AttributeKey<String> ATTRIBUTE_KEY_USER_ID = AttributeKey.valueOf(KEY_USER_ID);
    private   static ChannelGroup GlobalGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private  static ConcurrentMap<String, ChannelId> ChannelMap=new ConcurrentHashMap();

    public static void setChannelParam(Channel channel,String userId){
        channel.attr(ATTRIBUTE_KEY_USER_ID).setIfAbsent(userId);
    }

    public  static void addChannel(Channel channel,String userId){
        setChannelParam(channel,userId);
        GlobalGroup.add(channel);
//        ChannelMap.put(userId,channel);
    }
    public static void removeChannel(Channel channel){
        GlobalGroup.remove(channel);
//        ChannelMap.remove(channel.id().asShortText());
    }
    public static  Channel findChannel(String id){
        return GlobalGroup.find(ChannelMap.get(id));
    }

    public static void sendToOne(final String userId,TextWebSocketFrame tws){
        GlobalGroup.stream().forEach(x->{
            String itemUserId = x.attr(ATTRIBUTE_KEY_USER_ID).get();
            if (userId.equals(itemUserId)){
                x.writeAndFlush(tws);
            }
        });
    }
    public static void send2All(TextWebSocketFrame tws){
        GlobalGroup.writeAndFlush(tws);
    }
}
